package com.dts.servlet;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "helloServlet", urlPatterns = "/hello", loadOnStartup = 1,
        initParams = {@WebInitParam(name = "username", value = "admin")})
public class HelloServlet extends HttpServlet {
    private ServletConfig config;
    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("Servlet正在初始化。。。。。");
        this.config = config;
    }
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        Object user = request.getSession().getAttribute("user");
        if (user != null) {
            response.getWriter().write("<p>欢迎你，" + user + "</p>");
        } else {
            response.getWriter().write("没有权限");
            return;
        }

        PrintWriter out = response.getWriter();
        out.write("<p>用户名：" + this.config.getInitParameter("username") + "</p>");
        out.write("<p>密码：" + this.config.getInitParameter("password") + "</p>");
        out.close();
    }
}